package com.yanchangapp.ui.activity.base;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.yanchangapp.R;
import com.yanchangapp.model.bean.Version;
import com.yanchangapp.ui.service.DownloadService;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.ui.base.BasePresenter;
import com.zxl.baselib.util.ui.UIUtils;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
@RuntimePermissions
public class UpdateActivity extends BaseActivity {
    private LinearLayout mLlClose;
    private ImageView mIvClose;
    private TextView mTvTitle,mTvInfo;
    private Button mBtnUpdate;
    private Version mVersion;
    private RelativeLayout rlUpdate;
    /**
     * 是否强制更新
     */
    private boolean isForce = false;

    public static void show(Activity activity, Version version){
        Intent intent = new Intent(activity,UpdateActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("version",version);
        intent.putExtras(bundle);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);

    }

    @Override
    protected void init() {
        mVersion = (Version) getIntent().getSerializableExtra("version");
        if (mVersion.getIsForced() == 1){
            isForce = true;
        }else {
            isForce = false;
        }
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_update;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        mLlClose = findViewById(R.id.ll_close);
        mIvClose = findViewById(R.id.iv_close);
        mTvTitle = findViewById(R.id.tv_title);
        mTvInfo = findViewById(R.id.tv_update_info);
        mBtnUpdate = findViewById(R.id.btn_ok);
        rlUpdate = findViewById(R.id.rlUpdate);

        if (isForce){
            mLlClose.setVisibility(View.GONE);
        }
        mTvTitle.setText(getString(R.string.update_version_title,mVersion.getVersionName()));
        mTvInfo.setText(mVersion.getDescription());
    }

    @Override
    protected void initData() {
        getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 设置返回动画为空
        overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
    }

    @Override
    protected void initListener() {
        mBtnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rlUpdate.setVisibility(View.GONE);
                UpdateActivityPermissionsDispatcher.needPermissionWithPermissionCheck(UpdateActivity.this);
            }
        });

        mIvClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 结束
                finish();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            if (isForce){
                // 消费
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    // 权限申请已经完毕了...

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void needPermission() {
        UIUtils.showToast("进行下载更新");
        DownloadService.startService(UpdateActivity.this,mVersion.getDownloadUrl());
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        UpdateActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onShowRationale(final PermissionRequest request) {
        showPSMaterialDialog(null, "需要开启大桥对您手机的存储权限才能下载安装，是否现在开启", "确定", "取消",
                new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        request.proceed();
                    }
                }, new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        request.cancel();
                    }
                });
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onDenied() {
        showPSMaterialDialog("权限说明", "未取得大桥对您手机的存储权限，无法下载安装", "赋予权限", "", new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
                UpdateActivityPermissionsDispatcher.needPermissionWithPermissionCheck(UpdateActivity.this);
            }
        },null);
    }

    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onNerverAsk() {
        showPSMaterialDialog(null, "未取得大桥对您手机的存储权限，无法下载安装。请前往应用权限设置打开权限", "去打开", "", new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
                UpdateActivity.this.getAppDetailSettingIntent();
            }
        },null);
    }
}
